package com.jd.platform.gobrs.worker.keylistener;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.jd.platform.gobrs.common.model.GCacheKeyModel;
import com.jd.platform.gobrs.common.rule.KeyRule;
import com.jd.platform.gobrs.worker.cache.CaffeineCacheHolder;
import com.jd.platform.gobrs.worker.rule.KeyRuleHolder;
import com.jd.platform.gobrs.worker.tool.SlidingWindow;

/**
 * @program: gobrs
 * @ClassName AbstractAutoKeyListener
 * @description:
 * @author: sizegang
 * @create: 2022-01-09 22:44
 * @Version 1.0
 **/
public abstract class AbstractAutoKeyListener implements IKeyListener {
    public static final String SPLITER = "-";
    public static final String NEW_KEY_EVENT = "new key created event, key : ";

    public static final String DELETE_KEY_EVENT = "key delete event key : ";

    @Override
    public void newKey(GCacheKeyModel hotKeyModel, KeyEventOriginal orignal) {
        //cache里的key
        String key = buildKey(hotKeyModel);
        doNewKey(hotKeyModel, orignal, key);
    }


    public String buildKey(GCacheKeyModel hotKeyModel) {
        return Joiner.on(SPLITER).join(hotKeyModel.getAppName(), hotKeyModel.getKeyType(), hotKeyModel.getKey());
    }

    public abstract void doNewKey(GCacheKeyModel hotKeyModel, KeyEventOriginal orignal, String key);

    /**
     * 生成或返回该key的滑窗
     */
    public SlidingWindow createWindowOrDirectReturn(GCacheKeyModel hotKeyModel, String key) {
        //取该key的滑窗
        return (SlidingWindow) CaffeineCacheHolder.getCache(hotKeyModel.getAppName()).get(key, (Function<String, SlidingWindow>) s -> {
            // 先获取key 如果没有则说明 当前key 没有配置规则 但是会分配一个
            KeyRule keyRule = KeyRuleHolder.getRuleByAppAndKey(hotKeyModel);
            return new SlidingWindow(keyRule.getInterval(), keyRule.getThreshold());
        });
    }
}
